package com.wits.qso.service;

import java.text.NumberFormat;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.wits.platform.service.BaseService;
import com.wits.qso.dao.VmDao;
import com.wits.qso.entity.Vm;

@Component
public class VmService extends BaseService<Vm, String>
{
	private VmDao vmDao = null;
	protected static final Logger logger = LoggerFactory.getLogger( Vm.class );

	/**
	 * 注入班级dao
	 * @param clsDao
	 */
	@Autowired
	public void setVmDao(VmDao vmDao) {
		this.baseDao = vmDao;
		this.vmDao = vmDao;		
	}

	public Vm findByUserId(String vmUserId) {
		return vmDao.findByUserId(vmUserId);
	}

	public boolean hasVmByIp(String vmIp) {
		return null != vmDao.findByIp( vmIp );
	}
	
	public int batchVmData(Workbook workbook, String currentUserId) {
		int result = 0;
		Sheet sheet = workbook.getSheetAt( 0 );
		try {
			for (int i = 1; i < sheet.getPhysicalNumberOfRows(); i++) {
				Row row = sheet.getRow( i );
				Vm vm=new Vm();
				vm.setName((String)getCellValue(row.getCell(0)));
				vm.setIp((String)getCellValue(row.getCell(1)));
				vm.setPwd((String)getCellValue(row.getCell(2)));
				vm.setPort((String)getCellValue(row.getCell(3)));
				vm.setIsEnable((String)getCellValue(row.getCell(4)));
				vm.setRemark((String)getCellValue(row.getCell(5)));
				if(vmDao.findByIp(vm.getIp())==null){
					this.save(vm);
					result++;
				}
			}
		}catch(Throwable cause) {
			logger.error( cause.getMessage(), cause );
		}
		return result;
	}
	
	private Object getCellValue(Cell cell) {
		Object result = null;
		if (null != cell) {
			switch (cell.getCellType()) {
				case Cell.CELL_TYPE_STRING:
					result = cell.getRichStringCellValue().getString();
					break;
				case Cell.CELL_TYPE_NUMERIC:
					if (DateUtil.isCellDateFormatted( cell )) {
						result = cell.getDateCellValue();
					} else {
						NumberFormat nf = NumberFormat.getInstance();
						nf.setGroupingUsed( false );
						result = String.valueOf( nf.format( cell.getNumericCellValue() ) );
					}
					break;
			}
		}

		return result;
	}
}
